#!/usr/bin/python
# -*- coding: utf-8 -*-

import uuid
from manager.user_manager import UserManager
import web.page
from web.response import Response
from web.request import Request
from web.session import Session
from model.user import User
import utils.log_utils as log 


class Login(object):
    def handle(self, req, resp):  
        output = web.page.render('login.html', {'username':u'亲'}) 
        return resp.respond(output)

class LoginHandler(object):
    def handle(self, req, resp):  
        email, passwd = req.args.get('email'), req.args.get('passwd')
        error_url, query_url = '/demo/error', '/demo/query'
        if not email or not passwd or email == '' or passwd == '': 
            return resp.redirect(req, error_url)
        else:
            user = User(email, passwd) 
            manager = UserManager()
            authed = manager.auth(user)
            if authed:
                session = Session(req)
                session['login'] = True
                session['username'] = email
                session['token'] = uuid.uuid4().get_hex()
                session.save()
                resp.set_cookie('s_id', session.s_id)
                return resp.redirect(req, query_url)
            else:
                return resp.redirect(req, error_url)

